package com.lc.midi.mid;

import java.io.*;

public class MidiFile {
	private BufferedInputStream bufferedInputStream;

	public MidiFile(File file) throws IOException {
		InputStream inputStream = new FileInputStream(file);
		bufferedInputStream = new BufferedInputStream(inputStream);
	}

	public MidiFile(String filepath) throws IOException {
		this(new File(filepath));
	}
	
//	public MidiFile(entity.Midi midi) {
//		InputStream inputStream = new ByteArrayInputStream(midi.getData());
//		bufferedInputStream = new BufferedInputStream(inputStream);
//	}
	
	public BufferedInputStream getMidiStream() {
		return bufferedInputStream;
	}
	
	public int read(byte[] b) throws IOException, MidiException {
		int len = bufferedInputStream.read(b);
		//if (len <= 0 && b.length != 0)
		if (len != b.length)
			throw new MidiException("read len error");
		return len;
	}
	
	public int readAutoNum() throws IOException, MidiException {
		int b = 0;
		readLen = 0;
		int ans = 0;
		do {
			ans *= 128;
			b = bufferedInputStream.read();
			if (b < 0)
				throw new MidiException("read len < 0");
			ans += (b & 0x7f);
			readLen++;
		} while ((b & 0x80) == 0x80);
		return ans;
	}

	private int readLen = 0;
	
	public int getReadAutoNumLen() {
		return readLen;
	}
}
